# ========================================
# FlorisBoard → CocoKeyboard 自动批量替换
# ========================================

$ErrorActionPreference = "Continue"
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $projectRoot

Write-Host "开始批量替换 FlorisBoard -> CocoKeyboard..." -ForegroundColor Cyan
Write-Host ""

# 定义替换规则（按优先级排序，先替换长的，再替换短的）
$replacements = @(
    # 包名（最高优先级）
    @{ Pattern = 'dev\.patrickgold\.florisboard'; Replacement = 'com.coco.cocokeyboard'; Description = '包名(点)' },
    @{ Pattern = 'dev/patrickgold/florisboard'; Replacement = 'com/coco/cocokeyboard'; Description = '包名(/)' },
    @{ Pattern = 'dev\\patrickgold\\florisboard'; Replacement = 'com\coco\cocokeyboard'; Description = '包名(\)' },
    
    # 特定类名（精确匹配）
    @{ Pattern = '\bFlorisApplication\b'; Replacement = 'CocoApplication'; Description = 'FlorisApplication类' },
    @{ Pattern = '\bFlorisImeService\b'; Replacement = 'CocoImeService'; Description = 'FlorisImeService类' },
    @{ Pattern = '\bFlorisAppActivity\b'; Replacement = 'CocoAppActivity'; Description = 'FlorisAppActivity类' },
    @{ Pattern = '\bFlorisPreferenceModel\b'; Replacement = 'CocoPreferenceModel'; Description = 'FlorisPreferenceModel类' },
    @{ Pattern = '\bFlorisPreferenceStore\b'; Replacement = 'CocoPreferenceStore'; Description = 'FlorisPreferenceStore类' },
    @{ Pattern = '\bFlorisScreen\b'; Replacement = 'CocoScreen'; Description = 'FlorisScreen类' },
    @{ Pattern = '\bFlorisEmojiCompat\b'; Replacement = 'CocoEmojiCompat'; Description = 'FlorisEmojiCompat类' },
    @{ Pattern = '\bFlorisRef\b'; Replacement = 'CocoRef'; Description = 'FlorisRef类' },
    @{ Pattern = '\bFlorisLocale\b'; Replacement = 'CocoLocale'; Description = 'FlorisLocale类' },
    @{ Pattern = '\bFlorisRect\b'; Replacement = 'CocoRect'; Description = 'FlorisRect类' },
    
    # 通用 FlorisXxx 模式
    @{ Pattern = '\bFloris([A-Z][a-zA-Z0-9]*)'; Replacement = 'Coco$1'; Description = 'FlorisXxx类名' },
    
    # FlorisBoard 完整词
    @{ Pattern = '\bFlorisBoard\b'; Replacement = 'CocoKeyboard'; Description = 'FlorisBoard' },
    
    # 全大写
    @{ Pattern = '\bFLORISBOARD\b'; Replacement = 'COCOKEYBOARD'; Description = 'FLORISBOARD' },
    @{ Pattern = '\bFLADDONS\b'; Replacement = 'COCOADDONS'; Description = 'FLADDONS' },
    
    # 小写 + 下划线
    @{ Pattern = '\bfloris_app\b'; Replacement = 'coco_app'; Description = 'floris_app' },
    @{ Pattern = '\bfloris_'; Replacement = 'coco_'; Description = 'floris_前缀' },
    
    # 全小写（最后处理）
    @{ Pattern = '\bflorisboard\b'; Replacement = 'cocokeyboard'; Description = 'florisboard' },
    
    # URL 和路径中的 florisboard
    @{ Pattern = 'florisboard\.org'; Replacement = 'cocokeyboard.com'; Description = 'florisboard.org' },
    @{ Pattern = '/florisboard/'; Replacement = '/cocokeyboard/'; Description = '/florisboard/' },
)

# 文件类型
$extensions = @('*.kt', '*.kts', '*.xml', '*.gradle', '*.json', '*.md', '*.txt', '*.toml', '*.pro', '*.properties')

# 排除目录
$excludeDirs = @('.git', '.gradle', '.idea', '.kotlin', 'build', 'node_modules')

Write-Host "[1/2] 扫描文件..." -ForegroundColor Yellow

# 获取所有需要处理的文件
$allFiles = @()
foreach ($ext in $extensions) {
    $files = Get-ChildItem -Path $projectRoot -Filter $ext -Recurse -File -ErrorAction SilentlyContinue | 
        Where-Object { 
            $path = $_.FullName
            $excluded = $false
            foreach ($dir in $excludeDirs) {
                if ($path -like "*\$dir\*") {
                    $excluded = $true
                    break
                }
            }
            !$excluded
        }
    $allFiles += $files
}

Write-Host "   找到 $($allFiles.Count) 个文件" -ForegroundColor Green
Write-Host ""

Write-Host "[2/2] 执行替换..." -ForegroundColor Yellow

$modifiedCount = 0
$totalReplacements = 0
$processedCount = 0

foreach ($file in $allFiles) {
    $processedCount++
    
    # 显示进度
    if ($processedCount % 50 -eq 0) {
        Write-Host "   进度: $processedCount / $($allFiles.Count)" -ForegroundColor DarkGray
    }
    
    try {
        $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8 -ErrorAction Stop
        $originalContent = $content
        $fileModified = $false
        $fileReplacements = 0
        
        # 应用所有替换规则
        foreach ($rule in $replacements) {
            $pattern = $rule.Pattern
            $replacement = $rule.Replacement
            
            # 检查是否匹配
            if ($content -match $pattern) {
                # 执行替换
                $newContent = $content -replace $pattern, $replacement
                
                # 计算替换次数
                $matches = [regex]::Matches($content, $pattern)
                if ($matches.Count -gt 0) {
                    $fileReplacements += $matches.Count
                    $content = $newContent
                    $fileModified = $true
                }
            }
        }
        
        # 如果文件被修改，写回文件
        if ($fileModified) {
            Set-Content -Path $file.FullName -Value $content -Encoding UTF8 -NoNewline
            $modifiedCount++
            $totalReplacements += $fileReplacements
            
            $relativePath = $file.FullName.Substring($projectRoot.Length + 1)
            Write-Host "   ✓ $relativePath ($fileReplacements 处)" -ForegroundColor Gray
        }
    }
    catch {
        Write-Host "   ✗ 失败: $($file.Name) - $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "✅ 替换完成！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "📊 统计：" -ForegroundColor Cyan
Write-Host "  • 扫描文件: $($allFiles.Count)" -ForegroundColor White
Write-Host "  • 修改文件: $modifiedCount" -ForegroundColor White
Write-Host "  • 替换次数: $totalReplacements" -ForegroundColor White
Write-Host ""
Write-Host "⚠ 下一步：" -ForegroundColor Yellow
Write-Host "  1. 执行: ./gradlew clean" -ForegroundColor White
Write-Host "  2. 在 Android Studio 中 File -> Sync Project" -ForegroundColor White
Write-Host "  3. 重新构建项目" -ForegroundColor White
Write-Host ""
